package com.seek.service.imp;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.seek.core.BaseServiceImpl;
import com.seek.dao.ActivityDao;
import com.seek.model.entity.TActivity;
import com.seek.service.ActivityService;
import com.seek.util.BeanUtils;
import com.seek.util.CommonUtil;
import com.seek.util.DateUtil;

@Repository("activityService")
public class ActivityServiceImpl extends BaseServiceImpl<TActivity> implements ActivityService {

	@Autowired
	public void setDao(ActivityDao activityDao) {
		super.setDao(activityDao);
	}
	public ActivityDao getDao() {
		return (ActivityDao) super.getDao();
	}
	
	@Transactional
	public TActivity save(JSONObject reqJson) throws Exception{
		TActivity en = new TActivity();
		if (CommonUtil.getLongValue((reqJson.getString("actId")))>0){
			en.setId(CommonUtil.getLongValue(reqJson.getString("actId")));
		}
		en.setComapnyId(reqJson.getLong("companyId"));
		en.setTitle(reqJson.getString("title"));
		en.setImageUrl(reqJson.getString("coverImg"));
		
		if (CommonUtil.isEmpty(en.getTitle()) || CommonUtil.isEmpty(en.getImageUrl()) || CommonUtil.isEmpty(reqJson.getString("startTime"))
				|| CommonUtil.isEmpty(reqJson.getString("endTime"))){
			throw new Exception("缺少必须的参数，请检查");
		}
		en.setBeginTime(DateUtil.dateFormat(reqJson.getString("startTime"), DateUtil.DATE_FORMAT_YMDHMS));
		en.setEndTime(DateUtil.dateFormat(reqJson.getString("endTime"), DateUtil.DATE_FORMAT_YMDHMS));
		
		if (en.getId() == null || en.getId() < 1){
			en.setIsUsed(1);
			en.setStatus(0);
			en.setCreateTime(new Date());
			en.setCreateUserId(CommonUtil.getLongValue(reqJson.getString("_currnetUserId")));
			en.setModifyTime(new Date());
			en.setModifyUserId(en.getCreateUserId());
			en = this.getDao().insert(en);
		}else{
			en.setModifyTime(new Date());
			en.setModifyUserId(CommonUtil.getLongValue(reqJson.getString("_currnetUserId")));
			TActivity old = this.getDao().get(en.getId());
			BeanUtils.copyPropertiesExclude(en, old, new String[]{"id","companyId","status","createUserId","createTime","isUsed"});
			en = this.getDao().update(old);	
		}

		return en;
	}
}